<?php

namespace App\Jobs;

use App\Models\Address;
use App\Models\Cart;
use App\Models\Huopin;
use App\Models\Order;
use App\Models\OrderList;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class AddOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    protected $user_id;
    protected $ids;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($user_id,$ids)
    {
        $this->user_id=$user_id;
        $this->ids=$ids;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 将ids切割成数组,循环数组获得商品数据
        $carts=Cart::whereIn('id',explode(',',$this->ids))->with('goods','huopin')->get();
        $totalPrice=0;
        foreach($carts as $cart){
            $totalPrice+=$cart['goods']['price']*$cart['num'];
        }
        $address=Address::where('user_id',$this->user_id)->where('is_default',1)->first();
        // 新建订单数据
        $order=Order::create([
            'order_id'=>md5(time()),
            'totalPrice'=>$totalPrice,
            'address_id'=>$address['id'],
            'status'=>0,
            'user_id'=>$this->user_id
        ]);
        // 往订单列表中添加当前订单的列表数据
        foreach (explode(',',$this->ids) as $value){
            // 找到对应value值的购物车数据
            $cart=Cart::find($value);
            OrderList::create([
                'order_id'=>$order['id'],
                'goods_id'=>$cart['goods_id'],
                'huopin_id'=>$cart['huopin_id'],
                'num'=>cart['num']
        ]);
        // 将当前用户所购买的所有商品的对应货品的库存减少
            foreach(explode(',',$this->ids) as $value){
                // 找到对应的购物车数据
                $cart=Cart::find($value);
                // 找到对应的货品数据
                $huopin=Huopin::find($cart['huopin_id']);
                // 更新库存数据
                $huopin->update(['kucun'=>$huopin['kucun']-$cart['num']]);
                // 从购物车表中删除对应的购物车数据
                $cart->destroy($value);
            }

        }




    }

    public function fail($exception = null)
    {

    }
}
